import { Inject, Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ICoolCache, Cache } from 'midwayjs-cool-core';

import {
  AddressPageDto,
  CreateAddressDto,
  UpdateAddressDto,
} from '../dto/address';

import { CustomerAddressEntity } from '../entity/address';

@Provide()
export class CustomerAddressService {
  @InjectEntityModel(CustomerAddressEntity)
  customerAddressEntity: Repository<CustomerAddressEntity>;

  @Inject('cool:cache')
  coolCache: ICoolCache;

  async add(address: CreateAddressDto) {
    const doc = await this.customerAddressEntity.insert(address);
    return await this.customerAddressEntity.findOne(doc.raw.insertId, {
      select: [
        'id',
        'customerId',
        'name',
        'sex',
        'phone',
        'province',
        'city',
        'area',
        'street',
        'detail',
        'isDefault',
      ],
    });
  }

  async delete(addressId: number) {
    return await this.customerAddressEntity.delete(addressId);
  }

  async update(address: UpdateAddressDto) {
    return await this.customerAddressEntity.update(address.id, address);
  }

  @Cache(5)
  async info(addressId: number) {
    return await this.customerAddressEntity.findOne(addressId);
  }

  @Cache(5)
  async page(pageOp: AddressPageDto) {
    return await this.customerAddressEntity.find({
      where: { customerId: pageOp.customerId },
      skip: pageOp.start,
      take: pageOp.limit,
    });
  }
}
